<template>
	<view class="indent-detail">
		<view class="bgcc"></view>
		<view>
			<van-cell-group inset>
				<van-cell title="就餐地区" :value="region" >
					<template #right-icon> <view style="width: 32rpx; height: 32rpx;"></view> </template>
				</van-cell>
				 <!-- @click="showPopup('room')" is-link -->
				<van-cell title="就餐场合" :label="selectedRooms.map(e => e.name)"> 
					<template #right-icon> <view style="width: 32rpx; height: 32rpx;"></view> </template>
				</van-cell>
				<van-cell title="就餐时间" :value="!diningDate ? '请选择' : ''" :label="diningDate" @click="showPopupSelect('date')" is-link/>
				<van-cell title="就餐人数" :value="formData.dining_person_num || '请输入'" @click="showInputDialog('dining_person_num')" is-link/>
				<van-cell title="申请人" :value="formData.petitioner || '请输入'" @click="showInputDialog('petitioner')" is-link/>
				<van-cell title="费用归口部门" :value="formData.cost_target || '请输入'" @click="showInputDialog('cost_target')" is-link/>
				
				<van-cell title="来宾类型" :value="formData.guest_type.text || '请选择'" @click="showPopupSelect('guest_type')" is-link/>
				<van-cell title="接待等级" :value="formData.reception_estate || '请选择'" @click="showPopupSelect('reception_estate')" is-link/>
				<van-cell title="备注" label="备注" use-label-slot>
					<template #label>
						<van-field
							type="textarea"
							placeholder="请输入备注"
							autosize
							:border="false"
							@input="handleRemarkInput"
						/>
					</template>
				</van-cell>
			</van-cell-group>
		</view>

		<view style="margin-top: 20rpx; padding-bottom: 160rpx;">
			<van-cell-group inset>
				<van-cell title="ELEGRP餐厅"/>
				<view class="goods">
					<block v-for="(it, i) in shoppingCart" :key="it._id">
						<goodsCardVue isShopCart :goods="it" @onChangeGoods="handleChangeGoods($event, i)"/>
					</block>
				</view>
			</van-cell-group>
		</view>
		<van-submit-bar
		  :price="totalpPrice * 100"
		  button-text="提交订单"
		  @submit="onSubmit"
		>	
			<template>
				<button v-if="isFormVerifySuccess" class="share" @click="handleShareIndent">
					<van-icon name="share-o" size="50rpx" />
				</button>
			</template>
			<template #tip v-if="formData.dining_person_num">
				<p>
					就餐人数: {{formData.dining_person_num}}人, 人均: {{perCapita}}元
				</p>
			</template>
		</van-submit-bar>
		
		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="popupDialogRef" mode="input" :title="'输入'+inputDialogConfig.title"
				placeholder="请输入" @confirm="handleInputConfirm">
			</uni-popup-dialog>
		</uni-popup>
		
		<van-popup
		  round
		  :show="isShowPopup"
			close-on-click-overlay
		  position="bottom"
			lock-scroll
			@click-overlay="isShowPopup = false"
		>
			<selectAppointmentDateVue 
				v-if="popupType === 'date'" 
				:modelValue.sync="formData.dining_date"
				:dining_place="formData.dining_place"
				:appointment_date="appointment_date"
				:appointment_date_origin="appointment_date_origin"
				ref="selectAppointmentDateRef"
				@close="isShowPopup = false"
				@selectRoom="showPopupSelect_Date"
			/>
			<van-picker
				v-else-if="['guest_type', 'reception_estate'].includes(popupType)"
			  :columns="columns"
			  :default-index="0"
				show-toolbar
				value-key="text"
			  @confirm="pickerConfirm"
				@cancel="isShowPopup = false"
			/>
		</van-popup>
	</view>
</template>

<script>
	import { mapState, mapGetters } from "vuex"
	import wPickerVue from "@/components/w-picker/w-picker.vue";
	import goodsCardVue from '../order/cpns/goods-card.vue';
	import selectRoomImgVue from "./cpns/select-room-img.vue";
	import selectAppointmentDateVue from "./cpns/select-appointment-date.vue";
	import {date2Text} from '@/utils/date2Text.js'
	const db = uniCloud.database()
	const orderFormDB = db.collection('dish-order-form')
	const reg = /^\d*$/
	const mapTmplId = {
		orderSuccess: 'uo7jdEa8dcocHYewvo6way0jVzpBkT4Z8Hrx5KgvoMM',
		approve: 'Q0nQCGwQob36aGkr8hMT0lquJ8ACqHumW3g5b-CE5oA'
		// indentCancel: 'mIzEx7pXKxkcPaOtUvQTRKv0hRoztL32A1_9keRnhB0'
	}
	export default {
		name: 'indent-detail',
		data() {
			return {
				isShowPopup: false,
				formData: {
					dining_place: [],
					dining_date: [],
					dining_person_num: '',
					petitioner: '',
					cost_target: '',
					guest_type: '',
					reception_estate: '',
					user_remark: ''
				},
				guest_type_config: [],
				reception_estate_config: [
					"一级接待",
					"二级接待",
					"三级接待",
					"四级接待",
					"五级接待"
				],
				mapInputDialog: {
					dining_person_num: '就餐人数',
					petitioner: '申请人',
					cost_target: '费用归口部门',
				},
				appointment_date: {},
				inputDialogConfig: {
					title: '',
					activeKey: ''
				},
				appointment_date_origin: [],
				popupType: '',
				columns: []
			};
		},
		computed: {
			...mapState({
				region: s => s.order.region,
				userInfo: s => s.user.userInfo,
				selectedRooms: s => s.order.selectedRooms
			}),
			...mapGetters(['shoppingCart', 'totalpPrice']),
			diningDate() {
				return this.formData.dining_date.map(e => {
					if (!e) return ''
					const [year, time] = e.split(' ')
					return date2Text(year) + ' ' + time
				}).filter(Boolean).join(" - ")
			},
			perCapita() {
				return (this.totalpPrice / this.formData.dining_person_num).toFixed(2)
			},
			isFormVerifySuccess() {
				return Object.keys(this.formData).every(k => {
					if (k === 'user_remark') return true
					const e = this.formData[k]
					if (Array.isArray(e)) {
						return e.length
					} else if (typeof e === 'object') {
						return Object.keys(e).length
					} else if (typeof e === 'number') {
						return e
					} else {
						return e.trim()
					}
				})
			}
		},
		components: {wPickerVue, goodsCardVue, selectRoomImgVue, selectAppointmentDateVue},
		onLoad() {
			this.selectRoom(this.selectedRooms)
			this.requestGuestType()
			uni.hideShareMenu()
		},
		methods: {
			async handleShareIndent(e) {
				const res = await this.handleSubmit(false, 0, true)
				uni.redirectTo({
					url: '/pages/indent-detail/indent-detail?&id=' + res.indent_id
				})
			},
			async onSubmit() {
				const flag = this.verifyFormData()
				if (!flag) return
				
				const tmplIds = Object.values(mapTmplId)
				wx.requestSubscribeMessage({
					tmplIds,
					success: (res) => {
						console.log('requestSubscribeMessage res', res);
						const subscriptionOrder = res[mapTmplId.orderSuccess] === 'accept';
						this.handleSubmit(subscriptionOrder)
					},
					fail: (err) => {
						console.log('requestSubscribeMessage err', err);
						this.handleSubmit(false)
					}
				})
				// wx.getSetting({
				// 	withSubscriptions: true,
				// 	success: (setting) => {
				// 		const {mainSwitch, itemSettings = {}} = setting.subscriptionsSetting
				// 		console.log(mainSwitch, itemSettings);
				// 		if (mainSwitch && tmplIds.every(k => itemSettings[k] === 'accept')) 
				// 			return this.handleSubmit(true)
				// 		wx.requestSubscribeMessage({
				// 			tmplIds,
				// 			success: (res) => {
				// 				console.log('requestSubscribeMessage res', res);
				// 				const subscriptionOrder = res[mapTmplId.orderSuccess] === 'accept';
				// 				this.handleSubmit(subscriptionOrder)
				// 			},
				// 			fail: (err) => {
				// 				console.log('requestSubscribeMessage err', err);
				// 				this.handleSubmit(false)
				// 				// 这里提醒重试
				// 			}
				// 		})
				// 	}
				// })
			},
			async handleSubmit(subscriptionOrder, status = 1, isShare = false) {
				const {
					dining_date, 
					dining_person_num, 
					petitioner,
					// dining_place, 
					user_remark,
					cost_target,
					guest_type,
					reception_estate,
				} = this.formData
				uni.showLoading({title: '加载中',mask: true});
				try{
					const order_form = {
						user_id: this.userInfo.openid,
						type: this.userInfo.role[0].role_id,
						status,
						total_fee: parseFloat(this.totalpPrice),
						dining_place: this.selectedRooms.map(e => e._id),
						dining_person_num,
						region: this.region,
						dining_date,
						petitioner,
						cost_target,
						guest_type: guest_type._id,
						reception_estate,
						user_remark,
					}
					const res = await uniCloud.callFunction({
						name: 'dish-order-form-create',
						data: {
							goods_list: this.shoppingCart,
							order_form,
							isShare
						}
					})
					if (res.result.code === 200) {
						uni.showToast({
							title: '下单成功'
						})
						this.$store.commit('clearShoppingCart', this.shoppingCart)
						uni.$emit('refreshIndentList')
						if (isShare) return res.result
						uni.redirectTo({
							url: '/pages/indent-detail/indent-detail?id=' + res.result.indent_id,
						})
						subscriptionOrder && await this.$store.dispatch('subscriptionMsg', res.result.indent_id)
					} else {
						throw ''
					}
					
				}catch(e){
					//TODO handle the exception
					console.log(e);
					uni.showToast({
						title: '服务器错误，请稍后重试',
						icon: 'error'
					})
				}
				uni.hideLoading()
			},
			verifyFormData() {
				if (!this.isFormVerifySuccess) {
					uni.showToast({
						title: '请完善表单',
						icon: 'none'
					})
					return false
				}
				return true
			},
			showInputDialog(activeKey) {
				this.inputDialogConfig = {
					activeKey, title: this.mapInputDialog[activeKey]
				}
				this.$refs.popupDialogRef.setVal(this.formData[activeKey])
				this.$refs.inputDialog.open()
			},
			handleInputConfirm(val) {
				const {activeKey} = this.inputDialogConfig
				val = val?.trim() || ''
				if (activeKey === 'dining_person_num') {
					if (reg.test(val)) {
						val = val ? Number(val) : val
					} else {
						uni.showToast({
							title: '请输入数字',
							icon: 'none'
						})
						return
					}
				}
				this.formData[activeKey] = val
				this.$refs.inputDialog.close()
			},
			reset_appointment_date() {
				this.appointment_date = {}
			},
			selectRoom(room) {
				this.formData.dining_place = room
				this.isShowPopup = false
			},
			handleChangeGoods(num, i) {
				const goods = this.shoppingCart[i]
				const isSpecification = goods.specification?.length
				if (isSpecification) {
					this.$store.commit('setSpecificationList', [goods, num])
				} else {
					this.$store.commit('changeGoodsNumByGoods', [num, goods])
				}
			},
			async requestGuestType() {
				const res = await db.collection('dish-order-form-guest-type').field('order,guest_type as text,_id as value').orderBy('order asc').get()
				this.guest_type_config = res.result.data
			},
			async showPopupSelect_Date(index = 0) {
				const {_id} = this.formData.dining_place[index]
				this.reset_appointment_date()
				this.$refs.selectAppointmentDateRef.dining_date_ = []
				uni.showLoading({title: '加载中',mask: true});
				const res = await db.collection('dish-dining-place').where({_id}).get()
				uni.hideLoading()
				this.appointment_date_origin = res.result.data[0].appointment_date
				this.appointment_date_origin.forEach((it) => {
					const [startDate, startTime] = it[0].split(' ')
					const [endDate, endTime] = it[1].split(' ')
					this.appointment_date[startDate] = 
						(this.appointment_date[startDate] || []).concat([[startTime, endTime]])
				}, {})
			},
			pickerConfirm(e) {
				const map = {
					// room: () => {
					// 	console.log(e);
					// 	this.formData.dining_place = e.detail.value
					// 	this.formData.dining_person_num = 1
					// 	this.formData.dining_date = []
					// },
					guest_type: () => {
						this.formData.guest_type = e.detail.value
					},
					reception_estate: () => {
						this.formData.reception_estate = e.detail.value
					}
				}
				map[this.popupType]()
				this.isShowPopup = false
			},
			async showPopupSelect(type) {
				// type: room date guest_type reception_estate
				this.isShowPopup = true
				this.popupType = type
				await this.$nextTick()
				const map = {
					room: () => {
						this.reset_appointment_date()
					},
					date: this.showPopupSelect_Date.bind(this),
					guest_type: () => {
						this.columns = this.guest_type_config
					},
					reception_estate: () => {
						this.columns = this.reception_estate_config
					}
				}
				map[type]()
			},
			handleRemarkInput(e) {
				this.formData.user_remark = e.detail
			}
		}
	}
</script>

<style lang="scss">
page {
	--button-danger-background-color: #004EA2;
	--button-danger-border-color: #004EA2;
	--tabs-bottom-bar-color: #004EA2;
	--submit-bar-button-height: 80rpx;
	--submit-bar-button-width: 220rpx;
	--button-normal-font-size: 28rpx;
	--font-weight-bold: 900;
	--submit-bar-price-font-size: 28rpx;
	--submit-bar-height: 100rpx;
}
.indent-detail {
	min-height: 90vh;
	padding: 30rpx 0 0;
	position: relative;
	background-color: #f4f4f4;
	.bgcc {
		width: 100vw;
		height: 600rpx;
		position: absolute;
		left: 0;
		top: 0;
		z-index: 0;
		// background-color: #004ea2;
		// background-image: linear-gradient(180deg, #004ea2 0%, #135eac 15%, #f4f4f4 100%);
	}
	
	.goods {
		background-color: white;
		padding: 10rpx 20rpx;
	}
	
	button.share{
		background: white;
		&::after {
			border: 0;
		}
	}
}
</style>
